package com.gg.fmallspringboot.controller;

import com.gg.fmallspringboot.entity.ProductSku;
import com.gg.fmallspringboot.entity.ShoppingCart;
import com.gg.fmallspringboot.model.Result;
import com.gg.fmallspringboot.requestvo.CartVo;
import com.gg.fmallspringboot.service.CarService;
import com.gg.fmallspringboot.service.impl.ProductSkuServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpRequest;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * 购物车controller
 */

@RestController
@RequestMapping("/cart")
public class CartController {

    @Autowired
    private ProductSkuServiceImpl pssi;
    private CarService carService;

    public CartController(CarService carService) {
        this.carService = carService;
    }

    @GetMapping("/allCart")
    public List<ShoppingCart> getCarList(){
        return carService.carList();
    }

    @GetMapping("/orderCart")
    public Result getOrderCart(String carIds,Integer userId){
    return carService.getOrderCar(carIds,userId);
    }

    @PutMapping("/updateCart")
    public Result updateCart(@RequestBody CartVo cartVo){
        String carId = cartVo.getCardId();
        Integer num = Integer.parseInt(cartVo.getNum());
        ShoppingCart cart = (ShoppingCart)carService.getOneByCartId(carId).getData();
        ProductSku productSku = pssi.getOneById(cart.getSkuId());
        if (productSku.getStock()<Integer.parseInt(cart.getCartNum())+num){
            return new Result(1,"库存上限");
        }else if(Integer.parseInt(cart.getCartNum())+num<=0){
            return new Result(2,"购物车数量不能为0");
        }
        else {

            cart.setCartNum(Integer.parseInt(cart.getCartNum())+num+"");

            Result result = carService.update(cart);
            return result;
        }

    }

}
